﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CLab.Common.Objects;
using System.Data;
using System.Collections;
using CLab.Common.Constantes;
using CLab.Utils.Extensions;

namespace CLab.Base
{
    public class PageBase : System.Web.UI.Page
    {
        private System.Web.UI.Control ctrFilter;
        #region Propiedades
        public CrystalDecisions.Shared.ParameterFields ReportViewerParams
        {
            get
            {
                if (Session["ReportViewerParams"] == null)
                {
                    Session["ReportViewerParams"] = new CrystalDecisions.Shared.ParameterFields();
                }

                return (CrystalDecisions.Shared.ParameterFields)Session["ReportViewerParams"];
            }
            set
            {
                Session["ReportViewerParams"] = value;
            }
        }

        public DataTable ReportDataSorce
        {
            get
            {
                if (Session["ReportDataSorce"] == null)
                {
                    Session["ReportDataSorce"] = new DataTable();
                }

                return (DataTable)Session["ReportDataSorce"];
            }
            set
            {
                Session["ReportDataSorce"] = value;
            }
        }

        public string ReportName
        {
            get
            {
                return Session["ReportName"].ToString();
            }
            set
            {
                Session["ReportName"] = value;
            }
        }

        public UsuarioLogin SessionUsuario
        {
            get
            {
                if (Session["Usuario"] == null)
                {
                    Session["Usuario"] = new UsuarioLogin();
                }

                return (UsuarioLogin)Session["Usuario"];
            }
            set
            {
                Session["Usuario"] = value;
            }
        }

        private List<Parametro> SessionParametros
        {
            get
            {
                if (Session["Parametros"] == null)
                {
                    return new List<Parametro>();
                }
                return (List<Parametro>)Session["Parametros"];
            }
            set { Session["Parametros"] = value; }
        }

        public List<Parametro> ViewParametros
        {
            get
            {
                if (ViewState["Parametros"] == null)
                {
                    return new List<Parametro>();
                }
                return (List<Parametro>)ViewState["Parametros"];
            }
            set { ViewState["Parametros"] = value; }
        }

        public string SessionUrlOriginal
        {
            get
            {
                if (Session["UrlOriginal"] != null)
                    return Session["UrlOriginal"].ToString();
                else
                    return "";
            }
            set { Session["UrlOriginal"] = value;
                //ViewState["UrlOriginal"] = value;
                //if (Page.Master != null)
                //{
                //    if (Page.Master.FindControl("hdnUrlOrigen") != null)
                //    {
                //        (((HiddenField)Page.Master.FindControl("hdnUrlOrigen"))).Value = value;
                //    }
                //}
            }
        }

        public string UrlOrigen
        {
            get
            {
                if (Page.Master != null)
                {
                    if (Page.Master.FindControl("hdnUrlOrigen") != null)
                        return (((HiddenField)Page.Master.FindControl("hdnUrlOrigen"))).Value;
                    else
                        return string.Empty;
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        public Laboratorio SessionLaboratorio
        {
            get
            {
                if (Session["Laboratorio"] == null)
                {
                    Session["Laboratorio"] = new Laboratorio();
                }

                return (Laboratorio)Session["Laboratorio"];
            }
            set
            {
                Session["Laboratorio"] = value;
            }
        }

        public int IdItem
        {
            get
            {
                if (ViewState["IdItem"] == null)
                {
                    return 0;
                }
                return (int)ViewState["IdItem"];
            }
            set { ViewState["IdItem"] = value; }
        }

        private List<System.Web.UI.Control> SessionCtrlFilter
        {
            get
            {
                if (Session[Page.ToString()] == null)
                    return new List<System.Web.UI.Control>();
                return (List<System.Web.UI.Control>)Session[Page.ToString()];
            }
            set { Session[Page.ToString()] = value; }
        }
        #endregion

        #region Eventos Base
        protected override void OnLoad(EventArgs e)
        {
            //if (Request.QueryString.Count > 0)
            //{
            //    this.SessionUrlOriginal = this.Page.Request.Url.OriginalString;
            //}

            if (Page.ToString() != "ASP.account_login_aspx")
                setParametros();

            base.OnLoad(e);
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            if (SessionUsuario.IdSession == null && (Page.ToString() != "ASP.account_login_aspx" && Page.ToString() != "ASP.pagecommon_error_aspx"))
            {
                if (Page.Master.ToString() == "ASP.popup_master")
                {
                    EjecutaJavaScript("try{ window.parent.location.reload(); } catch(err){alert('El sistema no puede redireccionarse a la pantalla de login, favor de salir de sesión manualmente')}", Page.IsPostBack == true ? false : true);
                }
            }

            if (SessionCtrlFilter.Count > 0 && !Page.IsPostBack)
            {
                if (ViewParametros.Count > 0)
                {
                    if (getParameter("SetFilters").ToString().Equals("true"))
                    {
                       SetFiltersValues();
                    }
                }

                Session.Remove(Page.ToString());
            }

            base.OnLoadComplete(e);
        }

        protected override void OnPreInit(EventArgs e)
        {
            if (Page.ToString() != "ASP.account_login_aspx")
            {
                Page.Theme = string.IsNullOrEmpty(SessionLaboratorio.Tema) ? "Default" : SessionLaboratorio.Tema;
                base.OnPreInit(e);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            // Verifico si la session esta activa
            if (SessionUsuario.IdSession == null && (Page.ToString() != "ASP.account_login_aspx" && Page.ToString() != "ASP.pagecommon_error_aspx"))
            {
                if (Page.Master.ToString() != "ASP.popup_master")
                {
                    //Response.Redirect(ResolveUrl("~/Account/Login.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Page.Request.Url + "?" + getParameters())), true);
                    //string url = UrlOrigen;
                    //if (string.IsNullOrEmpty(UrlOrigen))
                    //    url = this.Page.Request.Url.ToString();
                    Response.Redirect(ResolveUrl("~/Account/Login.aspx?ReturnUrl=" + HttpUtility.UrlEncode(this.Page.Request.Url.ToString())), true);
                }
                else
                {
                    ClientScript.RegisterClientScriptBlock(typeof(PageBase), "", "alert('La sesión a caducado, favor de iniciar sesión nuevamente');", true);
                }
            }

            base.OnInit(e);
            ////Verifico seguridad
            if (Page.ToString() != "ASP.account_login_aspx" && Page.ToString() != "ASP.default_aspx" && Page.ToString() != "ASP.pagecommon_permiso_aspx" && Page.ToString() != "ASP.pagecommon_error_aspx")
            {
                if (SessionUsuario.IdSession != null)
                {
                    GandA.Component.Security.PermisoItem pi = new GandA.Component.Security.PermisoItem();
                    GandA.Component.Security.Permisos p = new GandA.Component.Security.Permisos("BD");
                    pi = p.ObtenPermisoItem(IdItem, SessionUsuario.Perfil);
                    if (pi.PermisoAcceso == 0)
                    {
                        Response.Redirect("~/PageCommon/Permiso.aspx", false);
                    }
                }
            }
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
        }
        #endregion

        #region Metodos comunes
        private void SetFiltersValues()
        {
            foreach (System.Web.UI.Control ctrl in SessionCtrlFilter)
            {
                ctrFilter = null;
                FindSectionFilters(Page.Controls);
                if (ctrFilter != null)
                {
                    SetFilterValue(ctrFilter.Controls, ctrl);
                    ClientScriptManager cs = this.Page.ClientScript;
                    cs.RegisterStartupScript(typeof(Page), "btnBuscar", "document.getElementById('" + ((System.Web.UI.WebControls.Button)ctrFilter.FindControl("BtnBuscar")).ClientID + "').click()", true);
                }
            }
        }

        private void SetFilterValue(System.Web.UI.ControlCollection _controls, System.Web.UI.Control ctrl)
        {
            foreach (System.Web.UI.Control control in _controls)
            {
                if (control.GetType() == typeof(GandA.Web.UI.Controls.TextBox))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.TextBox) control).Text = ((GandA.Web.UI.Controls.TextBox) ctrl).Text;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.CheckBox))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.CheckBox)control).Checked = ((GandA.Web.UI.Controls.CheckBox)ctrl).Checked;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.ComboBox))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.ComboBox)control).SelectedValue = ((GandA.Web.UI.Controls.ComboBox)ctrl).SelectedValue;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.DatePicker))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.DatePicker)control).Text = ((GandA.Web.UI.Controls.DatePicker)ctrl).Text;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.ListBox))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.ListBox)control).SelectedValue = ((GandA.Web.UI.Controls.ListBox)ctrl).SelectedValue;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.TextBoxNumeric))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.TextBoxNumeric)control).Text = ((GandA.Web.UI.Controls.TextBoxNumeric)ctrl).Text;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.DropDownList))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.DropDownList)control).SelectedValue = ((GandA.Web.UI.Controls.DropDownList)ctrl).SelectedValue;
                    }
                }

                if (control.GetType() == typeof(GandA.Web.UI.Controls.TextBoxPassword))
                {
                    if (control.ID == ctrl.ID)
                    {
                        ((GandA.Web.UI.Controls.TextBoxPassword)control).Text = ((GandA.Web.UI.Controls.TextBoxPassword)ctrl).Text;
                    }
                }

                SetFilterValue(control.Controls, ctrl);
            }
        }

        public void SaveFilters()
        {
            if (Page.Master != null)
            {
                if (Page.Master.ToString() == "ASP.sitesearch_master")
                {
                    ctrFilter = null;
                    FindSectionFilters(Page.Controls);
                    if (ctrFilter != null)
                    {
                        SessionCtrlFilter = new List<Control>();
                        SaveControlValues(ctrFilter.Controls);
                    }
                }
            }
        }

        private void FindSectionFilters(System.Web.UI.ControlCollection _controls)
        {
            foreach (System.Web.UI.Control control in _controls)
            {
                if (control.GetType() == typeof(System.Web.UI.WebControls.ContentPlaceHolder) && control.ID == "cphFilter")
                {
                    ctrFilter = control;
                    break;
                }

                FindSectionFilters(control.Controls);
            }
        }

        private void SaveControlValues(System.Web.UI.ControlCollection _controls)
        {
            foreach (System.Web.UI.Control control in _controls)
            {
                if (control.GetType() == typeof(GandA.Web.UI.Controls.TextBox) || control.GetType() == typeof(GandA.Web.UI.Controls.CheckBox)
                    || control.GetType() == typeof(GandA.Web.UI.Controls.ComboBox) || control.GetType() == typeof(GandA.Web.UI.Controls.DatePicker)
                    || control.GetType() == typeof(GandA.Web.UI.Controls.DropDownList) || control.GetType() == typeof(GandA.Web.UI.Controls.ListBox)
                    || control.GetType() == typeof(GandA.Web.UI.Controls.TextBoxNumeric) || control.GetType() == typeof(GandA.Web.UI.Controls.TextBoxPassword))
                {
                    int index = SessionCtrlFilter.IndexOf(control);
                    if (index > -1)
                        SessionCtrlFilter[index] = control;
                    else
                        SessionCtrlFilter.Add(control);
                }

                SaveControlValues(control.Controls);
            }
        }

        public Configuracion ObtenConfiguracion(int idConfiguracion)
        {
            Configuracion config = new Configuracion();
            ArrayList parametros = new ArrayList();
            ConsultaServiceReference.ConsultaServiceClient srv = new ConsultaServiceReference.ConsultaServiceClient();

            parametros.Add(CreaParametroConsulta("@pnIdLaboratorio", SessionLaboratorio.IdLaboratorio, ConsultaServiceReference.Parameter.vEnumType.Int));
            parametros.Add(CreaParametroConsulta("@pnIdConfiguracion", idConfiguracion, ConsultaServiceReference.Parameter.vEnumType.Int));

            ConsultaServiceReference.Parameter[] prms = new ConsultaServiceReference.Parameter[parametros.Count];
            parametros.CopyTo(prms);

            DataSet ds= srv.EjecutaConsultaConParametros("spObtenConfiguracion", prms);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow row = ds.Tables[0].Rows[0];
                config.IdConfiguracion = Common.Util.Convert.ToInt(row[Columnas.IdConfiguracion]);
                config.IdConfiguracion = Common.Util.Convert.ToInt(row[Columnas.IdLaboratorio]);
                config.Descripcion = row[Columnas.Descripcion].ToString();
                config.Valor1 = (object)row[Columnas.Valor1];
                config.Valor2 = (object)row[Columnas.Valor3];
                config.Valor3 = (object)row[Columnas.Valor3];
            }

            return config;
        }

        public void EjecutaJavaScript(string script, bool esEnLoad)
        {
            if (!esEnLoad)
            {
                ////RegisterOnSubmitStatement("javascrip","<script type='text/javascript'>" + script + "</script>");
                ClientScript.RegisterClientScriptBlock(typeof(PageBase), "javascript", script, true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(PageBase), "javascript", script, true);
            }
        }

        public ConsultaServiceReference.Parameter CreaParametroConsulta(string _nombreParametro, object _valor, ConsultaServiceReference.Parameter.vEnumType _type)
        {
            ConsultaServiceReference.Parameter p = new ConsultaServiceReference.Parameter();
            p.nombreParametro = _nombreParametro;
            p.valor = _valor;
            p.type = _type;

            return p;
        }

        private void setParametros()
        {
            if (this.ViewParametros.Count == 0)
            {
                Parametro oParam;
                this.ViewParametros = new List<Parametro>();
                for (int i = 0; i < Request.QueryString.Count; i++)
                {
                    oParam = new Parametro();

                    oParam.Acceso = 1;
                    oParam.Nombre = Request.QueryString.GetKey(i);
                    oParam.Valor = HttpUtility.UrlDecode(Request.QueryString[oParam.Nombre]);

                    this.ViewParametros.Add(oParam);
                }

                //if (Request.QueryString.Count > 0)
                //{
                //    this.SessionUrlOriginal = this.Page.Request.Url.OriginalString;
                //    Response.Redirect(this.Page.Request.AppRelativeCurrentExecutionFilePath);
                //}
            }
            //else
            //{
            //    ViewParametros = SessionParametros;//.CloneParametros();
            //    SessionParametros = new List<Parametro>();
            //}
        }

        public object getParameter(string nameParameter)
        {
            object valor = null;
            if (ViewParametros.Count > 0)
            {
                valor = ViewParametros.Find(delegate(Parametro p) { return p.Nombre == nameParameter; }).Valor;
            }

            return valor;
        }

        public string getParameters()
        {
            string valor = string.Empty;
            foreach (Parametro param in ViewParametros)
            {
                valor = ViewParametros.Find(delegate(Parametro p) { return p.Nombre == param.Nombre; }).Valor + "&";
            }
            
            return string.IsNullOrEmpty(valor) ? "" : valor.Substring(1, valor.Length - 2);
        }

        #endregion
    }
}